package jnpf.property.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.property.entity.ZcglPropertyEquipmentEntity;
import jnpf.property.mapper.ZcglPropertyEquipmentMapper;
import jnpf.property.model.zcglpropertyequipment.ZcglPropertyEquipmentForm;
import jnpf.property.model.zcglpropertyequipment.ZcglPropertyEquipmentPagination;
import jnpf.property.service.ZcglPropertyEquipmentService;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * 抄表设备
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-12-03
 */
@Service
public class ZcglPropertyEquipmentServiceImpl extends ServiceImpl<ZcglPropertyEquipmentMapper, ZcglPropertyEquipmentEntity> implements ZcglPropertyEquipmentService {


        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;





    @Override
    public List<ZcglPropertyEquipmentEntity> getList(ZcglPropertyEquipmentPagination zcglPropertyEquipmentPagination){
        return getTypeList(zcglPropertyEquipmentPagination,zcglPropertyEquipmentPagination.getDataType());
    }
    @Override
    public List<ZcglPropertyEquipmentEntity> getTypeList(ZcglPropertyEquipmentPagination zcglPropertyEquipmentPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int zcglPropertyEquipmentNum =0;
        QueryWrapper<ZcglPropertyEquipmentEntity> zcglPropertyEquipmentQueryWrapper=new QueryWrapper<>();
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(zcglPropertyEquipmentPagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglPropertyEquipmentPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();
        int zcglPropertyEquipmentNum1 = 0;
        QueryWrapper<ZcglPropertyEquipmentEntity> zcglPropertyEquipmentSuperWrapper = new QueryWrapper<>();
        zcglPropertyEquipmentNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglPropertyEquipmentSuperWrapper,superQueryList,matchLogic,"zcglPropertyEquipment")
        ,new ZcglPropertyEquipmentEntity(),zcglPropertyEquipmentNum1);
            if (zcglPropertyEquipmentNum1>0){
            List<String> zcglPropertyEquipmentList =this.list(zcglPropertyEquipmentSuperWrapper).stream().map(ZcglPropertyEquipmentEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(zcglPropertyEquipmentList);
            intersectionSuperList.add(zcglPropertyEquipmentList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
				Object zcglPropertyEquipmentObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyEquipmentQueryWrapper,zcglPropertyEquipmentPagination.getMenuId(),"zcgl_property_equipment"));
            if (ObjectUtil.isEmpty(zcglPropertyEquipmentObj)){
                return new ArrayList<>();
            } else {
                zcglPropertyEquipmentQueryWrapper = (QueryWrapper<ZcglPropertyEquipmentEntity>)zcglPropertyEquipmentObj;
                zcglPropertyEquipmentNum++;
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object zcglPropertyEquipmentObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyEquipmentQueryWrapper,zcglPropertyEquipmentPagination.getMenuId(),"zcglPropertyEquipment"));
            if (ObjectUtil.isEmpty(zcglPropertyEquipmentObj)){
                return new ArrayList<>();
            } else {
            zcglPropertyEquipmentQueryWrapper = (QueryWrapper<ZcglPropertyEquipmentEntity>)zcglPropertyEquipmentObj;
            zcglPropertyEquipmentNum++;
			}


		}
    }
        if(isPc){
			if(ObjectUtil.isNotEmpty(zcglPropertyEquipmentPagination.getProject())){
            zcglPropertyEquipmentNum++;
                zcglPropertyEquipmentQueryWrapper.lambda().eq(ZcglPropertyEquipmentEntity::getProject,zcglPropertyEquipmentPagination.getProject());
                    }

			if(ObjectUtil.isNotEmpty(zcglPropertyEquipmentPagination.getEquipmentType())){
            zcglPropertyEquipmentNum++;
                zcglPropertyEquipmentQueryWrapper.lambda().eq(ZcglPropertyEquipmentEntity::getEquipmentType,zcglPropertyEquipmentPagination.getEquipmentType());
                    }

			if(ObjectUtil.isNotEmpty(zcglPropertyEquipmentPagination.getEquipmentName())){
            zcglPropertyEquipmentNum++;
            zcglPropertyEquipmentQueryWrapper.lambda().like(ZcglPropertyEquipmentEntity::getEquipmentName,zcglPropertyEquipmentPagination.getEquipmentName());
                    }

        }
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         zcglPropertyEquipmentQueryWrapper.lambda().in(ZcglPropertyEquipmentEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            zcglPropertyEquipmentQueryWrapper.lambda().and(t->t.in(ZcglPropertyEquipmentEntity::getId, finalAllSuperIDlist));
		}

        //排序
        if(StringUtil.isEmpty(zcglPropertyEquipmentPagination.getSidx())){
        zcglPropertyEquipmentQueryWrapper.lambda().orderByDesc(ZcglPropertyEquipmentEntity::getId);
        }else{
            try {
            	String sidx = zcglPropertyEquipmentPagination.getSidx();
                ZcglPropertyEquipmentEntity zcglPropertyEquipmentEntity = new ZcglPropertyEquipmentEntity();
				Field declaredField = zcglPropertyEquipmentEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 zcglPropertyEquipmentQueryWrapper="asc".equals(zcglPropertyEquipmentPagination.getSort().toLowerCase())?zcglPropertyEquipmentQueryWrapper.orderByAsc(value):zcglPropertyEquipmentQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<ZcglPropertyEquipmentEntity> page=new Page<>(zcglPropertyEquipmentPagination.getCurrentPage(), zcglPropertyEquipmentPagination.getPageSize());
                IPage<ZcglPropertyEquipmentEntity> userIPage=this.page(page, zcglPropertyEquipmentQueryWrapper);
                return zcglPropertyEquipmentPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<ZcglPropertyEquipmentEntity> list = new ArrayList();
                return zcglPropertyEquipmentPagination.setData(list, list.size());
            }
        }else{
            return this.list(zcglPropertyEquipmentQueryWrapper);
        }
    }


    @Override
    public ZcglPropertyEquipmentEntity getInfo(String id){
        QueryWrapper<ZcglPropertyEquipmentEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglPropertyEquipmentEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglPropertyEquipmentEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglPropertyEquipmentEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ZcglPropertyEquipmentEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglPropertyEquipmentForm form, int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		if (isUp){
			 id = form.getId();
		}
        if (total>0){
        return true;
        }
        return false ;
    }


}
